/**
 * 2018年12月17日下午3:34:48
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.DateKit;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.ShiroKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.dao.FangYuanDao;
import com.baihang.project.ds.entity.DanYuanEntity;
import com.baihang.project.ds.entity.LouDongEntity;
import com.baihang.project.ds.entity.TaoXingEntity;
import com.baihang.project.ds.model.FangYuanModel;

import redis.clients.jedis.Jedis;

@Service
public class FangYuanService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(FangYuanService.class);
	private Jedis jedis = RedisKit.getJedis();
	@Autowired
	private FangYuanDao dao;
	public List<LouDongEntity> getLouDong(){
		logger.info("查楼栋");
		List<FangYuanModel> model=new ArrayList<FangYuanModel>();
		if("1".equals(jedis.hmget("systemConfig","LoginTest").get(0))) {//免登录模式，没有任筹金额
			 model = dao.queryForFangYuanList("select * from room ");			
		}else {		
			if("1".equals(ShiroKit.getCurrentUser().getType())) {//管理人员
				 model = dao.queryForFangYuanList("select * from room ");
			}else {
				model = dao.queryForFangYuanList(String.format("select * from room where RcType=(select D_FromType from t_user where D_Tel='%s')",ShiroKit.getCurrentUser().getUserName()));								
			}
		}
		//根据楼栋进行分组
		TreeMap<String,List<FangYuanModel>> louDongMap= model.stream().collect(Collectors.groupingBy(FangYuanModel::getD_BanName,TreeMap::new,Collectors.toList()));
		List<LouDongEntity>  loudonglist = new ArrayList<LouDongEntity>();//存放楼栋
		for (Entry<String, List<FangYuanModel>> entry : louDongMap.entrySet()) {
			LouDongEntity  louDongEty = new LouDongEntity();//1创建楼栋
			louDongEty.setName(entry.getKey());//楼栋名称
			List<FangYuanModel> danYuanModel = entry.getValue();//1-1 获取楼栋下的单元
			//根据单元进行分组
			TreeMap<String,List<FangYuanModel>> danYuanMap = danYuanModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_Unit,TreeMap::new,Collectors.toList()));
			List<DanYuanEntity>  danYuanList = new ArrayList<DanYuanEntity>();//存放单元
			for(Entry<String,List<FangYuanModel>> entryDanYuan:danYuanMap.entrySet()) {
				DanYuanEntity danYuanEty = new DanYuanEntity();//2创建单元
				danYuanEty.setName(entryDanYuan.getKey());
				List<FangYuanModel> taoXingModel = entryDanYuan.getValue();//2-1 获取楼栋下的单元下面的套型
				//根据套型进行分组
				Map<Integer,List<FangYuanModel>> taoXingMap = taoXingModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column));
				List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
				for(Entry<Integer,List<FangYuanModel>> entryTaoXing:taoXingMap.entrySet()) {
					TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
					taoXingEty.setIndex(entryTaoXing.getKey());
					List<FangYuanModel> shiHaoModel = entryTaoXing.getValue();//3-1 获取室号
					taoXingEty.setShiHaoList(shiHaoModel);
					taoXingList.add(taoXingEty);//加入套型
				}				
				danYuanEty.setTaoxingList(taoXingList);
				danYuanList.add(danYuanEty);
			}
			louDongEty.setDanyuanList(danYuanList);
			loudonglist.add(louDongEty);
		}
		return loudonglist;
	}
	
	public List<DanYuanEntity> getDanYuan(String name){
		List<FangYuanModel> danYuanModel = dao.queryForFangYuanList(String.format("select * from room where D_BanName ='%s'",name));
		TreeMap<String,List<FangYuanModel>> danYuanMap = danYuanModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_Unit,TreeMap::new,Collectors.toList()));
		List<DanYuanEntity>  danYuanList = new ArrayList<DanYuanEntity>();//存放单元
		for(Entry<String,List<FangYuanModel>> entryDanYuan:danYuanMap.entrySet()) {
			DanYuanEntity danYuanEty = new DanYuanEntity();//2创建单元
			danYuanEty.setName(entryDanYuan.getKey());
			List<FangYuanModel> taoXingModel = entryDanYuan.getValue();//2-1 获取楼栋下的单元下面的套型
			//根据套型进行分组
			Map<Integer,List<FangYuanModel>> taoXingMap = taoXingModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column));
			List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
			for(Entry<Integer,List<FangYuanModel>> entryTaoXing:taoXingMap.entrySet()) {
				TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
				taoXingEty.setIndex(entryTaoXing.getKey());
				List<FangYuanModel> shiHaoModel = entryTaoXing.getValue();//3-1 获取室号
				taoXingEty.setShiHaoList(shiHaoModel);
				taoXingList.add(taoXingEty);//加入套型
			}				
			danYuanEty.setTaoxingList(taoXingList);
			danYuanList.add(danYuanEty);
		}
		return danYuanList;
	}
	
	public List<TaoXingEntity> getTaoXing(String loudongName,String danyuanName){
		List<FangYuanModel> taoXingModel = dao.queryForFangYuanList(String.format("select * from room where D_BanName ='%s' and D_Unit='%s'",loudongName,danyuanName));
		Map<Integer,List<FangYuanModel>> taoXingMap = taoXingModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column));
		List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
		for(Entry<Integer,List<FangYuanModel>> entryTaoXing:taoXingMap.entrySet()) {
			TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
			taoXingEty.setIndex(entryTaoXing.getKey());
			List<FangYuanModel> shiHaoModel = entryTaoXing.getValue();//3-1 获取室号
			taoXingEty.setShiHaoList(shiHaoModel);
			taoXingList.add(taoXingEty);//加入套型
		}			
		
		return taoXingList;
	}
	
	public FangYuanModel getXiangQing(int id) {
		FangYuanModel  model = dao.queryForFangYuan(String.format("select * from room where D_ID=%d", id));
		return model;
	}
	
	public String buyRoom(int id) {
		String result ="true";
		String msg="订购成功";
		/*int count = dao.queryForInt(String.format("select count(*) from room where D_state=2 and D_Operation='%s'",ShiroKit.getCurrentUser().getUserName()));
		if(count>0) {
			result="false";
			msg = "订购失败,您已达到认购上限(1套)";
		}else {*/
			//判断房源是否已售，
			int state = dao.queryForInt(String.format("select D_state from room where D_ID=%d",id));
			if(state==2) {//0、未售，1、预定，2、销售
				result="false";
				msg = "订购失败";
			}else {
				if("1".equals(jedis.hmget("systemConfig","IsTest").get(0))) {//测试模式不需要生成订单号
					dao.update(String.format("update room set D_state=2,D_Operation='%s',D_SaleDate='%s' where D_ID=%d", ShiroKit.getCurrentUser().getUserName(),DateKit.getCurrentDate(DateKit.Format_DateTime),id));	
				}else {
					//订单号 日期+用户手机
					String ddh = String.format("%s%s", DateKit.getCurrentDate(DateKit.Format_DateTime2),ShiroKit.getCurrentUser().getUserName());
					String operationRemark =String.format("S:/%s", DateKit.getCurrentDate(DateKit.Format_DateTime));
					dao.update(String.format("update room set D_state=2,D_Operation='%s',D_SaleDate='%s',D_SerialNumber='%s',D_OperationRemark='%s' where D_ID=%d", ShiroKit.getCurrentUser().getUserName(),DateKit.getCurrentDate(DateKit.Format_DateTime),ddh,operationRemark,id));					
				}
				jedis.sadd("rengou", ShiroKit.getCurrentUser().getUserName());//将认购成功的用户加入redis
			}
		//}
		return String.format("{\"result\":\"%s\",\"msg\":\"%s\"}", result,msg);
	}
	
	//推荐房源 从本人收藏的房源中取出未售房源中排第一的房源
	public Record getTuiJian() {
		Record rec = dao.queryForRecord(String.format("select r.*,t.Id,t.Sort from t_collection as t LEFT JOIN room as r on t.FieldId=r.D_ID  where t.UserName='%s' and r.D_state = 0 ORDER BY t.Sort LIMIT 1", ShiroKit.getCurrentUser().getUserName()));
		return rec;
	}
	
	//查询房源状态
	public String getFangYuanState(int id) {
		String state = dao.queryForString(String.format("select D_state from room where D_ID=%d", id));
		/*int count = dao.queryForInt(String.format("select count(*) from room where D_state=2 and D_Operation='%s'",ShiroKit.getCurrentUser().getUserName()));
		if(count >0) {
			state ="3";
		}*/
		return state;
	}
	
	
	
	//查询当前用户已经订购成功的套数
	public int alreadyBuyCount() {
		int count = dao.queryForInt(String.format("select count(*) from room where D_state=2 and D_Operation='%s'",ShiroKit.getCurrentUser().getUserName()));		
		return count;
	}
	/**
	 * 获取当前用户收藏的房源id集
	 */
	public String getShouCangFyIds() {
		List<Record> list = dao.queryForRecordList(String.format("select FieldId from t_collection where UserName='%s'", ShiroKit.getCurrentUser().getUserName()));
		//String result ="[]";
		StringBuilder sb = new StringBuilder("[");
		if(list.size()>0) {
			for(Record rec:list) {
				//sb.append(String.format("\"%d\",", rec.getInt("FieldId")));
				sb.append(String.format("%d,", rec.getInt("FieldId")));
			}
			sb.delete(sb.length()-1, sb.length());
			
		}
		sb.append("]");
		System.err.println("收藏is="+sb.toString());
		return sb.toString();
	}
	
	public void singleFanHong(int id) {
		//直接变蓝
		dao.update(String.format("update room set D_Monitor=2 where D_ID=%d",id));
		//随机变红
		Random random = new Random();
		long bianhong = random.nextInt(30);
		ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
          
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                    	 try {							
								TimeUnit.SECONDS.sleep(bianhong);
								System.err.println(bianhong+"线程操作");
								dao.update(String.format("update room set D_Monitor=3 where D_ID=%d",id));
							
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
                    }
                });
	}
	
	public boolean updateHouseState() {
		//将项目状态变更为自然结束
		int result = dao.update("update sys_config set Value='6' where Name='State'");
		if(result==0) {
			return false;
		}
		return true;
	}
	
	/**
	 * 根据房源id 锁定房源。先查询房源状态，满足未售时才锁定
	 * @param roomId
	 * @return
	 */
	public String userYuDingRoom(int roomId) {
		Record rec = dao.queryForRecord(String.format("select D_state,D_Monitor from room where D_ID=%d limit 1", roomId));
		int state = rec.getInt("D_state");
		int monitor = rec.getInt("D_Monitor");
		if(state==0 && monitor==0) {
			int count = dao.update(String.format("update room set D_state=1,D_Operation='%s',D_EditTime='%s' where D_ID='%d'", ShiroKit.getCurrentUser().getUserName(),DateKit.getCurrentDate(DateKit.Format_DateTime),roomId));
			if(count>0) {
				return JsonKit.toDoubleJson("true", "预定成功!");
			}else {
				return JsonKit.toDoubleJson("false", "预定失败!没有查到相应房源!");
			}
		}else if(state ==1||monitor==1 ||monitor==2) {
			return JsonKit.toDoubleJson("false", "预定失败!此房源已预定!");
		}else {
			return JsonKit.toDoubleJson("false", "预定失败!此房源已售出!");
		}
	}
	
		//重置房源状态，预定还原为未售
		public void reSetState(int roomId) {
			dao.update(String.format("update room set D_state=0,D_Operation=null,D_EditTime='%s' where D_Operation='%s' and D_state=1 and D_ID=%d", DateKit.getCurrentDate(DateKit.Format_DateTime),ShiroKit.getCurrentUser().getUserName(),roomId));
		}
		//将未售变为预定
		public void setState(int id) {
			dao.update(String.format("update room set D_state=1,D_Operation='%s' where D_ID='%d'", ShiroKit.getCurrentUser().getUserName(),id));
		}
}
